#ifndef __UTILS_HPP__
#define __UTILS_HPP__

#include <errno.h>
#include <unistd.h>

#include <cstring>

#define ERROR   "ERROR: "

namespace utils {

    static inline std::string strerror(int errnum)
    {
        char buf[32] = {0};
        return std::string(strerror_r(errnum, buf, 32));
    }

    class Fd {
    public:
        Fd(int fd)
            : m_fd(fd)
        {}

        virtual ~Fd()
        {
            close();
        }

        void close()
        {
            if (m_fd > 0) {
                ::close(m_fd);
                m_fd = 0;
            }
        }

        operator int()
        {
            return m_fd;
        }

    private:
        int m_fd;
    };

    class FdGuard {
    public:
        FdGuard(Fd &fd)
            : m_fd(fd)
        {}
        virtual ~FdGuard()
        {
            m_fd.close();
        }
        Fd &operator*()
        {
            return m_fd;
        }
        Fd *operator->()
        {
            return &m_fd;
        }
    private:
        Fd  &m_fd;
    };
};

#endif
